package com.etcbase.dcs.utils.gui;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.animation.Animator.AnimatorListener;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;

public class LayoutHeightAnimator {
	
	private int durationTime;
	private ViewGroup viewGroupLayout;
	private int startHeight;
	private int stopHeight;
	private int heightDifference;
	private AnimatorListener userAnimatorListener;
	
	public LayoutHeightAnimator( ViewGroup viewGroupLayout, int durationTime ) {
		this.viewGroupLayout = viewGroupLayout;
		this.durationTime = durationTime;
	}
			
	
	
	// start animating to the given target Height
	public void start( int stopHeight, AnimatorListener userAnimatorListener ) {
		this.userAnimatorListener = userAnimatorListener;
		startHeight = viewGroupLayout.getHeight();
		this.stopHeight = stopHeight;
		heightDifference = stopHeight - startHeight;
				
		ValueAnimator animator = new ValueAnimator();
		animator.setDuration(durationTime);
		animator.setIntValues( new int[] {0,0} ); // the values are irrelevant
		animator.addUpdateListener( animatorUpdateListener );
		animator.addListener( animatorListener );
		animator.start();
	}
	
	private void setLayoutHeight(int Height) {
		LayoutParams layoutParams = viewGroupLayout.getLayoutParams();
		layoutParams.height = Height;
		viewGroupLayout.setLayoutParams(layoutParams);
	}
	
	private AnimatorUpdateListener animatorUpdateListener = new AnimatorUpdateListener() {
		@Override
		public void onAnimationUpdate(ValueAnimator animation) {
			setLayoutHeight( (int) (startHeight + heightDifference * animation.getCurrentPlayTime() / durationTime) );
		}
	};
	
	private AnimatorListener animatorListener = new AnimatorListener() {
		@Override
		public void onAnimationStart(Animator animation) {
			if (userAnimatorListener != null)
				userAnimatorListener.onAnimationStart(animation);
		}

		@Override
		public void onAnimationRepeat(Animator animation) {
			if (userAnimatorListener != null)
				userAnimatorListener.onAnimationRepeat(animation);
		}

		@Override
		public void onAnimationEnd(Animator animation) {
			// set final values for the dimensions of the layout
			setLayoutHeight(stopHeight);
			
			// then call the users listener
			if (userAnimatorListener != null)
				userAnimatorListener.onAnimationEnd(animation);
		}

		@Override
		public void onAnimationCancel(Animator animation) {
			if (userAnimatorListener != null)
				userAnimatorListener.onAnimationCancel(animation);
		}
	};
}